import { useMenuStore, useUserStore } from '@/store'
import { Router } from 'vue-router'
import NProgress from 'nprogress' //
import useMenu from '@/hooks/menu'

export default function setupPermissionGuard(router: Router) {
  router.beforeEach(async (to, from, next) => {
    const menuStore = useMenuStore()
    const userStore = useUserStore()
    if ((!menuStore.getMenuInfo || !userStore.getUserInfo) && to.path !== '/login' && to.path !== '/error') {
      try {
        await userStore.getCurrentUser()
        await menuStore.getUserMenuList()
        if (menuStore.getMenuInfo && userStore.getUserInfo) {
          useMenu().createUserRouter(router)
          next({ ...to, replace: true })
        } else {
          next('/login')
        }
      } catch (error) {
        next('/login')
      }
    } else {
      next()
    }
    NProgress.done()
  })
}
